package com.villaday.idf.activity;

import android.content.Intent;
import androidx.appcompat.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.villaday.idf.R;
import com.villaday.idf.adapter.UpgradeVipGitPacgageAdapter;
import com.villaday.idf.base.BaseActivity;
import com.villaday.idf.custom.LoadingDialog;
import com.villaday.idf.model.SaveGroup;
import com.villaday.idf.model.feedbackEntity;
import com.villaday.idf.model.vipMembersEntity;
import com.villaday.idf.util.Constant;
import com.villaday.idf.util.LogeUtil;
import com.villaday.idf.util.OkHttpUtil;
import com.villaday.idf.util.PreferencesUtil;
import com.villaday.idf.util.ToastUtil;
import com.villaday.idf.util.ToolBarUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 添加分组
 */
public class AddGroupsActivity extends BaseActivity implements OkHttpUtil.OnDataListener {

    @BindView(R.id.toolbar_text)
    public Toolbar toolbar;
    @BindView(R.id.tv_add_groups)
    public TextView tvSelected;
    @BindView(R.id.tv_save)
    public TextView tvSave;
    @BindView(R.id.et_group_name)
    public EditText etGroupName;
    @BindView(R.id.et_rabit)
    public EditText etRait;


    private UpgradeVipGitPacgageAdapter recyclerViewAdapter;

    private Gson gson = new GsonBuilder().create();
    private String userId;
    private LoadingDialog loadingDialog;
    private int type; //0 表示添加分组 1 表示编辑分组
    private List<vipMembersEntity.BodyBean> SourceMemberList;
    private String GroupName;
    private String BrokerRabit;
    private String groudId;


    List<vipMembersEntity.BodyBean> smList; //返回后所有组员要进行筛选进行增删改

    List<String> delMember = new ArrayList<>();
    List<String> addMember = new ArrayList<>();

    private List<String> oldmemeber = new ArrayList<>();

    @Override
    protected int getViewResId() {
        return R.layout.activity_add_groups;
    }

    @Override
    protected void init() {
        userId = PreferencesUtil.getUserId(this);
        type = getIntent().getIntExtra("entrance", 0);
        ToolBarUtil.initToolBar(toolbar, type == 0 ? "添加分组" : "设置分组", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });
        if (type == 1) {
            SourceMemberList = gson.fromJson(getIntent().getStringExtra("groupMember"), new TypeToken<List<vipMembersEntity.BodyBean>>() {
            }.getType());
            GroupName = getIntent().getStringExtra("nickName");
            BrokerRabit = getIntent().getStringExtra("percent");
            groudId = getIntent().getStringExtra("groudId");
            for(vipMembersEntity.BodyBean d : SourceMemberList){
                oldmemeber.add(d.getId());
            }
        }

        updateData(type);

    }


    private void updateData(int type) {

        switch (type) {
            case 0:
                tvSelected.setText("");
                tvSave.setVisibility(View.GONE);
                break;

            case 1:
                tvSelected.setText("已选" + SourceMemberList.size() + "人");
                tvSave.setVisibility(View.VISIBLE);
                etGroupName.setText(GroupName);
                etRait.setText(BrokerRabit);
                break;
        }
    }


    @Override
    protected void loadData() {

/*        loadingDialog = LoadingDialog.newInstance("订单加载...");
        loadingDialog.show(getFragmentManager());*/
        getData();
    }


    private void getData() {
/*        String toJson = gson.toJson(new TransferRecored(userId, "1", pageSize + "", pageIndex + ""));
        OkHttpUtil.postJson(Constant.URL.GetUserTransferBalancePageList, DesUtil.encrypt(toJson), this);*/
    }


    @Override
    public void onResponse(String url, String json) {
        if (!TextUtils.isEmpty(json)) {
            if (Constant.URL.save_group.equals(url)) { //添加组成员
                dismissLoading();
                LogeUtil.e("save_group", json);
                feedbackEntity fbe = gson.fromJson(json, feedbackEntity.class);
                if (Constant.Strings.SUC.equals(fbe.getCode())) {
                    ToastUtil.initToast(this, "操作成功");
                    setResult(RESULT_OK);
                    finish();
                }
            } else if (Constant.URL.remove_group_members.equals(url)) {  //删除组成员

                LogeUtil.e("remove_group_members", json);
                feedbackEntity fbe = gson.fromJson(json, feedbackEntity.class);
                if (Constant.Strings.SUC.equals(fbe.getCode())) {
                    if (addMember.size() > 0 && !TextUtils.isEmpty(groudId)) {
                        requestAddMember(groudId, etGroupName.getText().toString().trim(), etRait.getText().toString().trim(), addMember);
                    } else {
                        dismissLoading();
                        ToastUtil.initToast(this, "操作成功");
                        setResult(RESULT_OK);
                        finish();
                    }
                }
            }
        }
    }


    @Override
    public void onFailure(String url, String error) {

    }

    private void dismissLoading() {
        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }
    }


    @OnClick({R.id.ll_add_groups_layout, R.id.tv_save})
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.ll_add_groups_layout: {
                if (type == 1) {
                    for (vipMembersEntity.BodyBean bean : SourceMemberList) {
                        bean.setSelected(true);
                        bean.setGroup(1);
                    }
                    startActivityForResult(new Intent(this, AddMemberActivity.class).putExtra("data", gson.toJson(SourceMemberList)), Constant.Code.AddGroup);
                } else {
                    startActivityForResult(new Intent(this, AddMemberActivity.class), Constant.Code.AddGroup);
                }
                break;
            }

            case R.id.tv_save: { //保存修改和编辑分组
                if (smList != null) {
                    for (vipMembersEntity.BodyBean entity : smList) {
                        if (entity.getGroup() == 1 && !entity.isSelected()) { //要删除的成员
                            delMember.add(entity.getId());
                        } else if (entity.getGroup() == 0 && entity.isSelected()) { //要新增的成员
                            addMember.add(entity.getId());
                        }
                    }
                }

                if (TextUtils.isEmpty(etGroupName.getText().toString().trim())) {
                    ToastUtil.initToast(this, "请输入组名");
                } else if (TextUtils.isEmpty(etRait.getText().toString().trim())) {
                    ToastUtil.initToast(this, "请输入分佣比例");
                } else {
                    switch (type) {
                        case 0: //添加分组
                            if (addMember.size() > 0) {
                                requestAddMember("", etGroupName.getText().toString().trim(), etRait.getText().toString().trim(), addMember);
                            } else {
                                ToastUtil.initToast(this, "请添加组员");
                            }
                            break;

                        case 1://编辑分组
                            if (delMember.size() > 0 && !TextUtils.isEmpty(groudId)) {
                                requestDelMember(groudId, delMember); //先删除后添加
                            } else if (delMember.size() == 0 && addMember.size() > 0 && !TextUtils.isEmpty(groudId)) {
                                //没有删除直接添加
                                requestAddMember(groudId, etGroupName.getText().toString().trim(), etRait.getText().toString().trim(), addMember);
                            } else if (delMember.size() == 0 && addMember.size() == 0 && !TextUtils.isEmpty(groudId)) {
                                requestAddMember(groudId, etGroupName.getText().toString().trim(), etRait.getText().toString().trim(), oldmemeber);
                            }
                            break;
                    }
                }

            }
        }

    }

    /**
     * 添加分组用户
     *
     * @param id
     * @param name
     * @param broker
     * @param list
     */
    private void requestAddMember(String id, String name, String broker, List<String> list) {
        loadingDialog = LoadingDialog.newInstance("提交中...");
        loadingDialog.show(getFragmentManager());
        Map<String, Object> map = new HashMap<>();
        OkHttpUtil.postJson(this, Constant.URL.save_group, new SaveGroup(id, name, broker, list), map, this);
    }

    /**
     * 移除分组用户
     *
     * @param id
     * @param list
     */
    private void requestDelMember(String id, List<String> list) {
        loadingDialog = LoadingDialog.newInstance("提交中...");
        loadingDialog.show(getFragmentManager());
        Map<String, Object> map = new HashMap<>();
        OkHttpUtil.postJson(this, Constant.URL.remove_group_members, new SaveGroup(id, list), map, this);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constant.Code.AddGroup) {
            if (resultCode == RESULT_OK) {
                String json = data.getStringExtra("entity");
                smList = gson.fromJson(json, new TypeToken<List<vipMembersEntity.BodyBean>>() {
                }.getType());
                int merber = 0;
                for (vipMembersEntity.BodyBean sm : smList) {

                    if (sm.isSelected()) {
                        merber = merber + 1;
                    }
                }
                if (merber != 0) {
                    tvSelected.setText("已选" + merber + "人");
                    tvSave.setVisibility(View.VISIBLE);
                } else {
                    if (type == 1) {
                        tvSave.setVisibility(View.VISIBLE);
                        tvSelected.setText("已选0人");
                    } else {
                        tvSave.setVisibility(View.GONE);
                        tvSelected.setText("");
                    }
                }
            }
        }
    }
}
